import React from "react";
import { Modal, message } from "antd";
import { Controlled as CodeMirror } from "react-codemirror2";
import sqlParser from "@mmzp/sql-parser";
import { FieldAndColumn, Field } from "src/utils/interface";

import "codemirror/addon/fold/foldcode.js"; // 代码折叠
import "codemirror/addon/fold/foldgutter.js"; // 代码折叠
import "codemirror/addon/fold/brace-fold.js"; // 代码折叠
import "codemirror/addon/fold/comment-fold.js"; // 代码折叠
import "codemirror/addon/selection/active-line.js"; // 当前行高亮
import "codemirror/lib/codemirror.js";
import "codemirror/mode/sql/sql.js";
// css
import "codemirror/addon/fold/foldgutter.css"; // 代码折叠
import "codemirror/addon/hint/show-hint.css"; // 自动提示
import "codemirror/lib/codemirror.css"; // 编辑器样式
import "codemirror/theme/idea.css"; // 主题: idea

const { useState } = React;

interface Props {
  visible: boolean;
  setVisible: (visible: boolean) => void;
  setValue: (fieldsAndColumns: FieldAndColumn[]) => void;
}

interface DataType {
  type: string;
  unsigned?: boolean;
}

const ImportSQLModal: React.FC<Props> = (props) => {
  const [value, setValue] = useState("");

  const getType = (dataType: DataType) => {
    const map = {
      FLOAT: "float32",
      DOUBLE: "float64",
      TIMESTAMP: "time.Time",
      DATETIME: "time.Time",
      CHAR: "string",
      VARCHAR: "string",
      BLOB: "string",
      TEXT: "string",
      JSON: "struct",
      TINYINT: "boolean",
      SMALLINT: dataType.unsigned ? "uint8" : "int8",
      MEDIUMINT: dataType.unsigned ? "uint16" : "int16",
      INT: dataType.unsigned ? "uint32" : "int32",
      BIGINT: dataType.unsigned ? "uint64" : "int64",
      ENUM: "enum",
    };
    // @ts-ignore
    return map[dataType.type];
  };

  const importSQL = (sql: string) => {
    const result = sqlParser.parse(sql);
    const fieldsAndColumns = result[0].columns
      .filter((item: any) => item.name !== undefined)
      .map((item: any) => {
        const field = {
          name: item.name,
          description: item.comment,
          type: getType(item.data_type),
        } as Field;
        if (field.type === "enum") {
          field.enum = item.data_type.params.map(
            (item: string, index: number) => ({
              index: index.toString(),
              value: item,
            })
          );
        }
        const fieldAndColumn = {
          fields: field,
          columns: {
            fieldName: item.name,
            columnName: item.name,
            columnType: item.data_type.type,
          },
        } as FieldAndColumn;
        return fieldAndColumn;
      });
    return fieldsAndColumns;
  };

  return (
    <Modal
      title="Import JSON"
      width={800}
      visible={props.visible}
      onOk={() => {
        try {
          const fieldsAndColumns = importSQL(value);
          props.setValue(fieldsAndColumns);
          props.setVisible(false);
        } catch (e) {
          message.error("请输入合法的 SQL 建表语句");
          console.error(e);
        }
      }}
      onCancel={() => props.setVisible(false)}
    >
      <CodeMirror
        value={value}
        options={{
          mode: "javascript",
          theme: "idea", // 主题配置
          lineNumbers: true, // 显示行号
          lineWrapping: true, // 自动换行
          styleActiveLine: true, // 选中行高亮
          matchBrackets: true, // 匹配括号
          indentUnit: 4, // 缩进配置（默认为2）
        }}
        onBeforeChange={(editor, data, v) => setValue(v)}
      />
    </Modal>
  );
};

export default ImportSQLModal;
